package cn.kgc.ossdemo.utils;

import cn.kgc.ossdemo.config.OSSProperties;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.InputStream;
import java.util.UUID;

public class AliyunOSSUtil {
//    @Value("${oss.file.endpoint}")
//    static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
//    @Value("${oss.file.keyid}")
//    static String accessKeyId = "LTAI4FuU38m8pkRX8e6W3efk";
//    @Value("${oss.file.keysecret}")
//    static String accessKeySecret = "oAXA3nymqodRseY7fD5GSlIB1c8BFT";
//    @Value("${oss.file.filehost}")
//    static String folderName = "test";
//    @Value("${oss.file.bucketname}")
//    static String bucketName = "bucket-crowd";

    public static String upload(InputStream inputStream, String oldfileName) {

        String endpoint = OSSProperties.ENDPOINT;
        String accessKeyId = OSSProperties.ACCESS_KEY_ID;
        String accessKeySecret = OSSProperties.ACCESS_KEY_SECRET;
        String bucketName=OSSProperties.BUCKET_NAME;
        String folderName=OSSProperties.FOLDER_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //生成新的文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + oldfileName;
        String fileURL = folderName + "/" + newFileName;
        // 上传文件流。
        try {
            ossClient.putObject(bucketName, fileURL, inputStream);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

        return fileURL;
    }
}